import * as echarts from "echarts";
import _ from "lodash";
// import StringUtil from '@qly/base/lib/utils/common/string';

//线，柱图
export function line_bar_chart(data: any, xAsix: any, baseSize: number) {
    var seriesData: any = [],
        legendData: any = [];
    data.forEach(function (item: any) {
        if (item.type === 'bar') {
            seriesData.push({
                name: item.name,
                data: item.data,
                type: 'bar',
                cursor: 'default',
                showBackground: item.showBackground ? item.showBackground : false,
                backgroundStyle: { color: '#3050AA' },
                barWidth: item.barWidth ? item.barWidth : .12 * baseSize,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                        [
                            { offset: 0, color: item.color[0] },
                            { offset: 1, color: item.color[1] }
                        ]
                    ),
                    barBorderRadius: item.barBorderRadius ? item.barBorderRadius : [50, 50, 0, 0]
                },
                xAxisIndex: item.xAxisIndex ? item.xAxisIndex : 0,
                yAxisIndex: item.yAxisIndex ? item.yAxisIndex : 0,
                stack: item.stack ? item.stack : '',
                z: item.z ? item.z : 1
            });
        } else if (item.type === 'line') {
            seriesData.push({
                name: item.name,
                data: item.data,
                type: 'line',
                cursor: 'default',
                tooltip: item.tooltip,
                emphasis: item.emphasis,
                smooth: item.smooth !== undefined ? item.smooth : true,
                symbol: item.symbol !== undefined ? item.symbol : 'none',
                symbolSize: item.symbolSize !== undefined ? item.symbolSize : 4,
                xAxisIndex: item.xAxisIndex ? item.xAxisIndex : 0,
                yAxisIndex: item.yAxisIndex ? item.yAxisIndex : 0,
                lineStyle: { color: item.color, width: .02 * baseSize, type: item.lineType ? item.lineType : 'solid' },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                        [
                            { offset: 0, color: item.areaColor ? item.areaColor[0] : 'rgba(0, 0, 0, 0)' },
                            { offset: 1, color: item.areaColor ? item.areaColor[1] : 'rgba(0, 0, 0, 0)' }
                        ]
                    )
                },
                z: item.z || 3
            });
        } else if (item.type === 'pictorialBar') {
            seriesData.push({
                name: item.name,
                data: item.data,
                type: 'pictorialBar',
                barCategoryGap: '0',
                cursor: 'default',
                symbol: 'path://M0,10 L10,10 C5.5,10 5.5,5 5,0 C4.5,5 4.5,10 0,10 z',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                        [
                            { offset: 0, color: item.color[0] },
                            { offset: 1, color: item.color[1] }
                        ]
                    )
                }
            });
        }
        legendData.push({
            name: item.name,
            icon: item.icon
        });
    });

    let option = {
        color: ['#0C77F8', '#FCE712', '#05E833', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'],
        grid: {
            left: .1 * baseSize,
            top: .55 * baseSize,
            right: .1 * baseSize,
            bottom: .1 * baseSize,
            containLabel: true
        },
        title: {
            text: '',
            textStyle: { color: '#02A7FD', fontSize: .12 * baseSize, fontWeight: 600 },
            subtext: '',
            subtextStyle: { color: '#fff', fontSize: .11 * baseSize, lineHeight: .45 * baseSize },
            left: .1 * baseSize,
            top: .08 * baseSize
        },
        legend: {
            show: true,
            type: 'plain',
            right: 0,
            top: .28 * baseSize,
            textStyle: { fontSize: .11 * baseSize, color: '#fff', padding: [4, 10, 2, 0] },
            // padding: [2, 0],
            itemGap: 5,
            itemWidth: .10 * baseSize,
            itemHeight: .10 * baseSize,
            data: legendData
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'none',//line
                lineStyle: { color: 'rgba(54, 106, 228, 0.7)', type: 'dashed' }
            },
            formatter: function (res: any) {
                let content = '';
                res.forEach(function (item: any) {
                    if (item.value !== '') {
                        if (item.seriesName.includes("占比")||item.seriesName.includes("率")) {
                            content += item.seriesName + '（' + item.axisValue + '）' + '：' + item.value + '%<br>';
                        } else {
                            content += item.seriesName + '（' + item.axisValue + '）' + '：' + item.value + '<br>';
                        }
                    }
                });

                return content;
            },
            backgroundColor: '#16767F',
            borderWidth: 0,
            textStyle: { color: '#fff', fontSize: .12 * baseSize }
        },
        xAxis: [
            {
                type: 'category',
                data: xAsix[0],
                axisTick: { show: false },
                axisLine: { show: true, lineStyle: { color: '#177B84' } },
                axisLabel: {
                    color: '#fff',
                    fontSize: .11 * baseSize,
                    formatter: function(item:any){
                        if(item.length>3){
                            return item.slice(0,3) + '...';
                        }else{
                            return item
                        }
                    }
                },
                splitLine: { show: false }
            }, {
                show: false,
                type: 'category',
                data: xAsix[1],
                axisTick: { show: false },
                axisLine: { show: true, lineStyle: { color: '#3D6AE2' } },
                axisLabel: { fontSize: .11 * baseSize, color: '#fff' },
                splitLine: { show: false },
                boundaryGap: false
            }
        ],
        yAxis: [
            {
                max: (range: any) => range.max < 5 ? 5 : undefined,
                axisTick: { show: false },
                axisLine: { show: true, lineStyle: { color: '#177B84' } },
                splitLine: { show: false },
                axisLabel: { fontSize: .11 * baseSize, color: '#fff' },
                /*interval: 100,*/
                splitNumber: 5
            },
            {
                show: false,
                axisTick: { show: false },
                axisLine: { show: true, lineStyle: { color: '#3D6AE2' } },
                axisLabel: { fontSize: .11 * baseSize, color: '#fff', formatter: '{value}%' },
                splitLine: { show: false },
                max: 100,
                splitNumber: 5
            }
        ],
        series: seriesData
    };

    return option;
}

//柱图-横向
export function bar_chart(data: any, xAsix: any, baseSize: number) {
    var seriesData: any = [];
    data.forEach(function (item: any) {
        seriesData.push({
            name: item.name,
            data: item.data,
            type: 'bar',
            cursor: 'default',
            barMaxWidth: .085 * baseSize,
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 1, 1, 1,
                    [
                        { offset: 0, color: (item || {}).color[0] },
                        { offset: 1, color: (item || {}).color[1] }
                    ]
                ),
                barBorderRadius: [0, 50, 50, 0]
            }
        });
    });

    let option = {
        color: ['#0C77F8', '#FCE712', '#05E833', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'],
        grid: {
            left: .4 * baseSize,
            top: .75 * baseSize,
            right: .05 * baseSize,
            bottom: .2 * baseSize
        },
        title: {
            text: '',
            textStyle: { color: '#02A7FD', fontSize: .12 * baseSize, fontWeight: 600 },
            subtext: '',
            subtextStyle: { color: '#fff', fontSize: .11 * baseSize, lineHeight: .45 * baseSize },
            left: .1 * baseSize,
            top: .08 * baseSize
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'none',//line
                lineStyle: { color: 'rgba(54, 106, 228, 0.7)', type: 'dashed' }
            },
            formatter: function (res: any) {
                let content = '';
                res.forEach(function (item: any) {
                    content += item.seriesName + '（' + item.axisValue + '）' + '：' + item.value + '<br>';
                });
                return content;
            },
            backgroundColor: '#366AE4',
            textStyle: { color: '#fff', fontSize: .12 * baseSize }
        },
        xAxis: {
            type: 'value',
            axisTick: { show: false },
            axisLine: { show: false, lineStyle: { color: '#3D6AE2' } },
            axisLabel: { show: false, fontSize: .11 * baseSize, color: '#fff' },
            splitLine: { show: false }
        },
        yAxis: [
            {
                type: 'category',
                data: xAsix[0],
                axisTick: { show: false },
                axisLine: { show: true, lineStyle: { color: '#3D6AE2' } },
                axisLabel: { fontSize: .11 * baseSize, color: '#fff' },
                splitLine: { show: false }
            }, {
                type: 'category',
                //offset:-.2*baseSize,
                data: xAsix[1],
                axisTick: { show: false },
                axisLine: { show: false, lineStyle: { color: '#3D6AE2' } },
                axisLabel: { fontSize: .11 * baseSize, color: '#fff' },
                splitLine: { show: false }
            }
        ],
        series: seriesData
    };

    return option;
}

//柱图-圆环
export function bar_circle_chart(baseSize: number) {
    let option = {
        tooltip: {},
        angleAxis: {
            max: 2,
            startAngle: 0,
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false }
        },
        radiusAxis: {
            type: 'category',
            data: ['资质证照', '过程控制', '人员管理', '环境卫生', '特殊项目'],
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { color: '#fff', fontSize: .1 * baseSize, interval: 0, rotate: 270, borderWidth: 2, borderColor: '#081641' },
            z: 10
        },
        polar: {
            center: ['50%', '50%'],
            radius: '90%'
        },
        series: [{
            type: 'bar',
            cursor: 'default',
            data: [
                {
                    name: '资质证照',
                    value: 10,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 1, 1, 0,
                            [
                                { offset: 0, color: '#e76900' },
                                { offset: 1, color: 'rgba(0, 0, 0, 0)' }
                            ]
                        )
                    }
                }, {
                    name: '过程控制',
                    value: 10,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 1, 1, 0,
                            [
                                { offset: 0, color: '#f7c001' },
                                { offset: 1, color: 'rgba(0, 0, 0, 0)' }
                            ]
                        )
                    }
                }, {
                    name: '人员管理',
                    value: 10,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 1, 1, 0,
                            [
                                { offset: 0, color: '#05e833' },
                                { offset: 1, color: 'rgba(0, 0, 0, 0)' }
                            ]
                        )
                    }
                }, {
                    name: '环境卫生',
                    value: 10,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 1, 1, 0,
                            [
                                { offset: 0, color: '#38d7e8' },
                                { offset: 1, color: 'rgba(0, 0, 0, 0)' }
                            ]
                        )
                    }
                }, {
                    name: '特殊项目',
                    value: 10,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 1, 1, 0,
                            [
                                { offset: 0, color: '#0291fd' },
                                { offset: 1, color: 'rgba(0, 0, 0, 0)' }
                            ]
                        )
                    }
                }
            ],
            coordinateSystem: 'polar',
            barWidth: .06 * baseSize,
            itemStyle: {
                borderWidth: 0
            }
        }]
    };

    return option;
}

//雷达图
export function radar_chart(data: any, indicator: Array<any>, baseSize: number, unit: any = '') {
    if (indicator.length == 0) {
        //至少有一个轴线
        indicator.push({});
    }
    let option = {
        title: {
            show: true, //显示策略，默认值true,可选为：true（显示） | false（隐藏）
            text: "", //主标题文本，'\n'指定换行
            x: "center", //水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
            y: "5%", //垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
            textAlign: null, //水平对齐方式，默认根据x设置自动调整，可选为： left' | 'right' | 'center
            textStyle: {
                fontSize: 18,
                color: ''
            }
        },
        tooltip: {
            formatter: function (res: any) {
                let content = '';
                res.value.forEach(function (item: any, index: number) {
                    if (indicator[index].tag) {
                        content += indicator[index].tag + '：' + item + unit + '<br>';
                    } else {
                        content += indicator[index].name + '：' + item + unit + '<br>';
                    }
                });
                return content;
            },
            backgroundColor: '#366AE4',
            textStyle: { color: '#fff', fontSize: .12 * baseSize }
        },
        legend: {
            show: false
        },
        radar: {
            startAngle: -12,
            radius: '70%',
            nameGap: .1 * baseSize,
            name: {
                textStyle: { color: '#fff', fontSize: .11 * baseSize }
            },
            splitNumber: 4,
            splitArea: { show: false },
            splitLine: { lineStyle: { color: ['#3D6AE2'] } },
            axisLine: { lineStyle: { color: '#3D6AE2' } },
            indicator: indicator,
            unit: unit
        },
        series: [{
            type: 'radar',
            data: data,
            cursor: 'default',
            lineStyle: {
                width: 1,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                    [
                        { offset: 0, color: '#E87001' },
                        { offset: 1, color: '#0291FD' }
                    ]
                )
            },
            itemStyle: { opacity: 0 },
            areaStyle: {
                opacity: 0.7,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                    [
                        { offset: 0, color: '#E87001' },
                        { offset: 1, color: '#0291FD' }
                    ]
                )
            }
        }]
    };

    return option;
}

function GetMapName(userAreaCode?:any){

    // 显示南宁市
    const AreaCode: any = {
        nanning: '450100',
        xingning: '450102',
        qingxiu: '450103',
        jiangnan: '450105',
        xixiangtang: '450107',
        liangqing: '450108',
        yongning: '450109',
        wuming: '450110',
        longan: '450123',
        mashan: '450124',
        shanglin: '450125',
        binyang: '450126',
        hengzhou: '450127'
      };
      let MapName = 'china';
      console.log("MapName",MapName);
      console.log("userAreaCode",userAreaCode);
      for (const i in AreaCode) {
        if (Object.prototype.hasOwnProperty.call(AreaCode, i)) {
            console.log("AreaCodei",i);
            console.log("AreaCodei",AreaCode[i]);
            console.log("userAreaCode.Substring(0,6)",(userAreaCode as string).substring(0,6));
          if (AreaCode[i] == (userAreaCode as string).substring(0,6)) {
            MapName = i;
            console.log("AreaCode[i] == userAreaCode.Substring(0,6)",i);
            break;
          }
        }
      }
      console.log("MapName",MapName);
    return MapName;
}

//中国地图
export function chinaMap(data: any, baseSize: number, userAreaCode:string="450100") {
    var mapName = GetMapName(userAreaCode);
    let option = {
        visualMap: {
            type: 'piecewise',
            // min: 0,
            // max: 1,
            // text: ['40', '0'],
            show: true,
            textGap: .03 * baseSize,
            textStyle: { color: '#fff', fontSize: .11 * baseSize },
            left: .2 * baseSize,
            bottom: 3,
            itemWidth: .09 * baseSize,
            itemHeight: .09 * baseSize,
            calculable: false,//手柄
            realtime: true,
            splitNumber: 4,
            hoverLink:true,
            inRange: {
                color: ['#49afdf', '#eccc2f', '#fefa01', '#ff2e00']
            }
        },
        geo: {
            map: mapName,
            label: {
                normal: { show: false },
                emphasis: { show: false }
            },
            aspectScale: 0.75,
            zoom: 1.25,
            layoutCenter: ['130%', '30%'],
            itemStyle: {
                normal: {
                    borderWidth: .5,
                    borderColor: '#0d78cb',
                    areaColor: "#0f225e"
                },
                emphasis: {
                    borderWidth: .5,
                    areaColor: "#0f225e"
                }
            },
            data: data
        },
        series: [
            {
                type: 'heatmap',
                data: data,
                coordinateSystem: 'geo',
                progressive: 1000,
                animation: false,
                pointSize: .05 * baseSize,
                blurSize: .04 * baseSize
            }
        ]
    };

    return option;
}

//中国地图2
export function chinaMap2(data: any, baseSize: number = 1, userAreaCode:string="450100") {
    var mapName = GetMapName(userAreaCode);
    const group = _.groupBy(data, i => i.field);
    const series = [];

    for (const key in group) {
        const data = group[key];
        const item = _.uniqBy(data, i => i.ico)[0];

        series.push({
            name: key,
            symbol: item.ico,
            symbolSize: 25,
            type: 'scatter',
            coordinateSystem: 'geo',
            itemStyle: {
                opacity: 1
            },
            label: {
                show: true,
                formatter: '+{@value}',
                color: '#fff',
                position: 'top',
                fontSize: .12 * baseSize
            },
            data: data.map(i => ({
                name: i.name,
                value: [...i.coord, i.value]
            }))
        });
    }

    let option = {
        legend: {
            show: true,
            orient: 'vertical',
            left: 'left',
            top: 'bottom',
            itemGap: 5,
            itemWidth: 20,
            itemHeight: 20,
            textStyle: {
                color: '#fff',
                fontSize: .12 * baseSize
            }
        },
        geo: {
            map: mapName,
            zoom: 1.25,
            aspectScale: 0.75,
            layoutCenter: ['130%', '30%'],
            label: {
                normal: { show: true, color: '#fff', fontSize: .12 * baseSize },
                emphasis: { show: true, color: '#fff', fontSize: .12 * baseSize }
            },
            itemStyle: {
                normal: {
                    borderWidth: .5,
                    borderColor: '#0d78cb',
                    areaColor: "#0f225e"
                },
                emphasis: {
                    borderWidth: .5,
                    areaColor: "#0f225e"
                }
            }
        },
        series: series
    };

    return option;
}

//饼图
export function pie_chart(data: any, baseSize: number) {
    let option = {
        color: ['#FFA41F', '#0291FD', '#06EC31'],
        tooltip: {
            formatter: function (res: any) {
                if (res.data.name !== '') {
                    return res.data.name + '：' + res.data.value;
                }
            },
            backgroundColor: '#366AE4',
            borderWidth: 0,
            textStyle: { color: '#fff', fontSize: .12 * baseSize }
        },
        series: [
            {
                type: 'pie',
                center: ['50%', '40%'],
                radius: ['45%', '62%'],
                avoidLabelOverlap: false,
                label: {
                    show: false
                },
                data: data
            }
        ]
    };

    return option;
}

//桑基图
export function sankey_chart(data: any, links: any, baseSize: number) {
    let option = {
        color: ['#CB8762', '#FFE056', '#F27E7E', '#93E1ED', '#5B6DD0', '#FCC601', '#B9ED93', '#F27EED'],
        series: [
            {
                type: 'sankey',
                cursor: 'default',
                left: .1 * baseSize,
                right: .1 * baseSize,
                top: .3 * baseSize,
                bottom: .3 * baseSize,
                nodeWidth: .04 * baseSize,
                nodeGap: .1 * baseSize,
                nodeAlign: 'justify',
                layoutIterations: 0,//设置为0时数据顺序和原始数据一致
                orient: 'vertical',
                animation: false,
                draggable: false,
                focusNodeAdjacency: true,
                label: {
                    color: '#fff',
                    fontSize: .12 * baseSize
                },
                lineStyle: {
                    color: 'source',
                    opacity: .5,
                    curveness: 0.5
                },
                data: data,
                links: links
            }
        ]
    };

    return option;
}

//高德地图
// function gaodeMap() {
//     var map = new AMap.Map('p-map', {
//         resizeEnable: true,
//         animateEnable: false,
//         buildingAnimation: false,
//         showLabel: false, //不显示地图文字标记
//         mapStyle: "amap://styles/b136312010deb973b77145a3d813738b",
//         zoom: 4,
//         center: [106.431454, 32.228435]
//     });

//     this.data = undefined;
//     let that = this;
//     that.markers = [];
//     function initPage(DistrictCluster, _data, index) {
//         var distCluster = new DistrictCluster({
//             map: map, //所属的地图实例
//             zIndex: 11,
//             autoSetFitView: false,
//             //topAdcodes:[130000, 110000],
//             boundsQuerySupport: true,
//             getPosition: function (item) {
//                 if (!item) return null;
//                 return item.coord;//返回经纬度
//             },
//             renderOptions: {
//                 getClusterMarkerPosition: DistrictCluster.ClusterMarkerPositionStrategy.AVERAGE_POINTS_POSITION,
//                 getClusterMarker: function (feature, dataItems, recycledMarker) {
//                     let num = 0;
//                     dataItems.forEach(function (item) {
//                         num += item.dataItem.value
//                     });
//                     if (dataItems.length > 0 && that.data[index]) {
//                         var label = {
//                             offset: new AMap.Pixel(0, -.56 * baseSize),
//                             direction: 'bottom',
//                             content: num
//                         };
//                         if (recycledMarker) {
//                             recycledMarker.setLabel(label);
//                             return recycledMarker;
//                         }
//                         let ico = new AMap.Icon({
//                             image: 'image/' + that.data[index].ico,
//                             size: new AMap.Size(.36 * baseSize, .36 * baseSize),
//                             imageSize: new AMap.Size(.36 * baseSize, .36 * baseSize)
//                         });
//                         let marker = new AMap.Marker({
//                             offset: new AMap.Pixel(-.18 * baseSize, -.36 * baseSize),
//                             label: label,
//                             icon: ico
//                         });
//                         that.markers.push(marker);
//                         return marker
//                     }
//                 },
//                 featureStyle: {
//                     strokeStyle: '#1583db',
//                     lineWidth: 2
//                 },
//                 featureStyleByLevel: {
//                     country: {
//                         fillStyle: 'rgba(30, 50, 113, 0.8)'
//                     },
//                     province: {
//                         fillStyle: 'rgba(30, 50, 113, 0.7)'
//                     },
//                     city: {
//                         fillStyle: 'rgba(30, 50, 113, 0.6)'
//                     },

//                     district: {
//                         fillStyle: 'rgba(30, 50, 113, 0.5)'
//                     }
//                 }
//             }
//         });
//         distCluster.setData(_data.data)
//     }

//     this.change = function (data) {
//         let zoom = 4;
//         zoom = (baseSize / 100 * 4).toFixed(3);
//         if (zoom < 3.5) {
//             zoom = 3.5
//         }
//         console.log(zoom)
//         map.remove(that.markers);
//         map.setZoom(zoom);
//         map.setCenter([106.431454, 32.228435]);
//         that.data = data;
//         AMapUI.load(['ui/geo/DistrictCluster', 'lib/$'], function (DistrictCluster, $) {
//             data.forEach(function (item, index) {
//                 initPage(DistrictCluster, item, index)
//             })
//         })
//     }
// }